<template>
  <div class="container">
    <Breadcrumb />
    <a-row>
      <a-card :style="{ width: '19%' }" title="所属组织">
        <div class="sszdbox">
          <a-tree
            :data="treeDatas"
            :field-names="fieldnames"
            @select="select($event)"
          />
        </div>
      </a-card>
      <a-card :style="{ width: '81%' }">
        <a-row>
          <a-col :flex="1">
            <a-form
              :model="formModel"
              :label-col-props="{ span: 6 }"
              :wrapper-col-props="{ span: 18 }"
            >
              <a-row :gutter="20">
                <a-col :span="5">
                  <a-form-item field="username" label="账号">
                    <a-input
                      v-model="formModel.username"
                      placeholder="请输入账号"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-form-item field="nickname" label="姓名">
                    <a-input
                      v-model="formModel.nickname"
                      placeholder="请输入姓名"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-form-item field="sex" label="性别">
                    <a-select
                      v-model="formModel.sex"
                      :options="sexs"
                      placeholder="请选择性别"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>

                <a-col :span="4">
                  <a-form-item field="userType" label="类型">
                    <a-select
                      v-model="formModel.userType"
                      placeholder="请选择用户类型"
                      ><a-option
                        v-for="item of userTypes"
                        :key="item.id"
                        :value="item.id"
                        >{{ item.name }}</a-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :span="5">
                  <a-space :size="18">
                    <a-button type="primary" @click="onPageChange(1)">
                      <template #icon>
                        <icon-search />
                      </template>
                      搜索
                    </a-button>
                    <a-button @click="reset">
                      <template #icon>
                        <icon-refresh />
                      </template>
                      重置
                    </a-button>
                  </a-space>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
        <a-divider style="margin-top: 0" />
        <a-row style="margin-bottom: 16px">
          <a-col :span="12">
            <a-space>
              <a-button @click="openAdd" type="primary">
                <template #icon>
                  <icon-plus />
                </template>
                新增
              </a-button>
              <a-button @click="openUpload"> 批量导入 </a-button>
              <a-button status="danger" @click="pldel"> 批量删除 </a-button>
            </a-space>
          </a-col>
          <a-col
            :span="12"
            style="display: flex; align-items: center; justify-content: end"
          >
            <a-space>
              <!-- <a-button
              @click="openUnlockAll()"
              type="primary"
              status="success"
              :disabled="!userIds || userIds.length <= 0"
            >
              批量解锁
            </a-button> -->
              <a-button @click="downloadUser">
                <template #icon>
                  <icon-download />
                </template>
                批量导出
              </a-button>
            </a-space>
          </a-col>
        </a-row>

        <a-table
          ref="userList"
          row-key="userId"
          v-model:selectedKeys="timetableId"
          :loading="loading"
          page-position="bottom"
          :pagination="pagination"
          :row-selection="rowSelection"
          :columns="columns"
          :data="renderData"
          :bordered="false"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        >
          <template #sex="{ record }">
            <template v-for="(item, index) in sexs">
              <span v-if="record.sex == item.value">{{ item.label }}</span>
            </template>
          </template>

          <template #userType="{ record }">
            {{ getAppointmentTypes(record.userType) }}
          </template>
          <template #createTime="{ record }">
            {{ formatDateTo(record.createTime) }}
          </template>
          <template #status="{ record }">
            {{ record.status == 1 ? '正常' : '停用' }}
          </template>

          <template #option="{ record }">
            <a-space :size="18">
              <a-button type="outline" @click="openRePass(record)">
                重置密码
              </a-button>

              <a-button @click="openEdit(record)" type="primary">
                编辑
              </a-button>
              <a-button
                status="danger"
                @click="openDelete(record)"
                v-if="record.username != 'admin'"
              >
                删除
              </a-button>
              <a-button
                status="danger"
                @click="stopUser(record)"
                v-if="record.username != 'admin'"
              >
                {{ record.status == 1 ? '停用' : '正常' }}
              </a-button>
            </a-space>
          </template>
        </a-table>
      </a-card>
    </a-row>
    <a-modal
      v-model:visible="addShow"
      @cancel="handleCancel"
      :on-before-ok="handleCheck"
      :mask-closable="false"
      unmountOnClose
      width="900px"
    >
      <template #title> 用户 </template>
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-row style="margin-bottom: 16px">
          <a-col :span="12">
            <a-form-item field="username" label="账号">
              <a-input
                v-model="addForm.username"
                size="large"
                placeholder="请输入账号"
                :disabled="addForm.userId ? true : false"
              />
            </a-form-item>
          </a-col>
          <a-col
            :span="12"
            :password="password"
            v-if="addForm.userId ? false : true"
          >
            <a-form-item field="password" label="密码">
              <a-input-password
                v-model="addForm.password"
                size="large"
                placeholder="请输入密码"
                :disabled="addForm.userId ? true : false"
              />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item field="nickname" label="姓名">
              <a-input
                v-model="addForm.nickname"
                size="large"
                placeholder="请输入姓名"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="sex" label="性别">
              <a-select
                v-model="addForm.sex"
                :options="sexs"
                placeholder="请选择性别"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="mobile" label="手机号">
              <a-input
                v-model="addForm.mobile"
                size="large"
                placeholder="请输入手机号"
              />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item field="userType" label="类型">
              <a-select v-model="addForm.userType" placeholder="请选择用户类型"
                ><a-option
                  v-for="item of userTypes"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.name }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="organizationId" label="班级">
              <a-tree-select
                :data="treeData"
                v-model="addForm.organizationId"
                placeholder="请选择班级"
                :field-names="rolesFieldsd"
              ></a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="expirationTime" label="到期时间">
              <a-date-picker
                v-model="addForm.expirationTime"
                style="width: 500px"
                show-time
                :time-picker-props="{ defaultValue: '09:09:06' }"
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <a-modal
      class="df"
      v-model:visible="uploadShow"
      @cancel="uploadCancel"
      :on-before-ok="uploadCheck"
      :mask-closable="false"
      unmountOnClose
      width="450px"
    >
      <template #title> 导入用户 </template>
      <a-form ref="uploadModel" :rules="uploadRules" :model="uploadForm">
        <a-row style="margin-bottom: 16px">
          <a-form-item field="userType" label="类型">
            <a-select
              v-model="uploadForm.userType"
              :field-names="rolesFields"
              placeholder="请选择用户类型"
            >
              <a-option
                v-for="item of userTypes"
                :key="item.id"
                :value="item.id"
                >{{ item.name }}</a-option
              >
            </a-select>
          </a-form-item>
          <a-form-item field="organizationId" label="班级">
            <a-tree-select
              :data="treeData"
              v-model="uploadForm.organizationId"
              :field-names="rolesFieldsd"
              placeholder="请选择班级"
              style="width: 400px"
            ></a-tree-select>
          </a-form-item>

          <a-form-item field="expirationTime" label="到期时间">
            <a-date-picker
              v-model="uploadForm.expirationTime"
              show-time
              style="width: 400px"
              :time-picker-props="{ defaultValue: '09:09:06' }"
              format="YYYY-MM-DD HH:mm:ss"
            />
          </a-form-item>

          <a-form-item field="file" label="文件">
            <a-upload
              class="upload_box"
              @change="onChange"
              accept=".xls,.xlsx"
              ref="uploadRef"
              :auto-upload="false"
              :limit="1"
            >
              <template #upload-button>
                <a-space>
                  <a-button type="primary">选择附件</a-button>
                  <a-button @click.stop="downloadTemplate">下载模板</a-button>
                </a-space>
              </template>
            </a-upload>
          </a-form-item>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts">
  export default {
    name: 'user',
  };
</script>
<script lang="ts" setup>
  import { computed, ref, reactive } from 'vue';
  import useLoading from '@/hooks/loading';
  import { useSelectionStore } from '@/store';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { Message, Modal } from '@arco-design/web-vue';
  import dayjs from 'dayjs';
  import {
    downloadTemplate,
    adminUserExport,
    importUser,
    userListd,
    UserRemove,
    UserSave,
    UserUpdate,
    resetPassword,
    classList,
    organizationTree,
    stopUserid,
  } from '@/api/userlist';
  const stopUser = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确定更改用户状态吗？',
      onOk() {
        stopUserid({
          disabled: item.status == 1 ? '11' : '1',
          userId: item.userId,
        }).then((res) => {
          if (res.code == 200) {
            Message.success({
              //   content: res.message,
              content: '操作成功',
            });
            pagination.current = 1;
            fetchData();
          }
        });
      },
    });
  };
  const treeData = ref([]);
  // import { majorTree } from '@/api/major.ts';
  const formatDateTo = (date) => {
    // 使用dayjs来处理日期
    return dayjs(date).format('YYYY年MM月DD日 HH:mm');
  };
  const { loading, setLoading } = useLoading(true);
  const timetableId = ref([]);
  const pldel = () => {
    if (timetableId.value.length == 0) {
      Modal.confirm({
        title: '提示',
        content: '请先选中要删除的用户？',
      });
    } else {
      Modal.confirm({
        title: '提示',
        content: '确定进行删除吗？',
        onOk() {
          Promise.all(
            timetableId.value.map((timetableId) => {
              return UserRemove({ userId: timetableId }).then((res) => {
                if (res.code == '200') {
                  return true; // 标记删除成功
                } else {
                  fetchData();
                  throw new Error('删除失败');
                }
              });
            })
          )
            .then((results) => {
              // 检查所有结果是否都为 true，表示删除成功
              if (results.every((result) => result === true)) {
                // 如果所有删除成功，显示成功提示
                Message.success({
                  content: '删除成功',
                });

                // 然后重新获取数据
                fetchData();
              }
            })
            .catch((err) => {
              fetchData();
              console.error('删除失败:', err);
            });
        },
      });
    }
    console.log('执行了飘了删除', timetableId.value);
  };
  const generateDataModel = () => {
    return {
      userId: '',
      username: '',
      nickname: '',
      password: '',
      sex: '',
      mobile: '',
      deptId: '',

      effectiveTime: '',
      organizationList: [],
      organizationId: '',
      // majorIdsArr: [],
    };
  };

  const rules = reactive({
    username: [
      {
        required: true,
        message: '请输入用户名',
      },
      {
        minLength: 4,
        message: '最少输入四位',
      },
      {
        maxLength: 20,
        message: '最长20位',
      },
    ],
    mobile: [
      {
        maxLength: 20,
        message: '最长20位',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
      },
      {
        minLength: 4,
        message: '最少输入四位',
      },
      {
        maxLength: 16,
        message: '最长16位',
      },
      {
        match: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*?])[^\s]{6,16}$/,
        message: '6-16位的,需包含大写字母、小写字母、特殊符号及数字',
      },
    ],
    nickname: [
      {
        required: true,
        message: '请输入姓名',
      },
      {
        maxLength: 20,
        message: '最长20位',
      },
    ],
    sex: [
      {
        required: true,
        message: '请选择性别',
      },
    ],
    userType: [
      {
        required: true,
        message: '请选择性别',
      },
    ],
    expirationTime: [
      {
        required: true,
        message: '请选择到期时间',
      },
    ],
  });
  const addForm = ref(generateDataModel());
  const addShow = ref(false);
  const addModel = ref();

  const openAdd = () => {
    classList().then((res) => {
      console.log('获取班级列表', res.data);
      treeData.value = res.data;
    });
    rules.password[0].required = true;
    rules.username[0].required = true;
    rules.sex[0].required = true;
    addForm.value = generateDataModel();
    addShow.value = true;
  };

  const handleCheck = (done) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          if (addForm.value.userId) {
            UserUpdate(addForm.value).then((res) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '编辑成功',
                });
                done(true);
                reset();
              } else {
                done(false);
              }
            });
          } else {
            UserSave(addForm.value).then((res) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '新增成功',
                });
                done(true);
                reset();
              } else {
                done(false);
              }
            });
          }
        } else {
          done(false);
        }
      }
    );
  };

  const openEdit = (item) => {
    rules.password[0].required = false;
    rules.username[0].required = false;
    rules.sex[0].required = false;
    let majorIdsArr = [];
    // if (item.majorIds) {
    //   majorIdsArr = item.majorIds.split(',');
    //   majorIdsArr = majorIdsArr.map((item) => {
    //     return +item;
    //   });
    // }
    addForm.value = Object.assign({}, item, {
      majorIdsArr: majorIdsArr,
    });
    classList().then((res) => {
      console.log('获取班级列表', res.data);
      treeData.value = res.data;
    });
    addShow.value = true;

    // console.log('ss', rules.username[0].required);
  };

  const handleCancel = () => {
    addShow.value = false;
  };
  const openDelete = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除吗？',
      onOk() {
        UserRemove({
          userId: item.userId,
        }).then((res) => {
          if (res.code == '200') {
            Message.success({
              //   content: res.message,
              content: '删除成功',
            });
            pagination.current = 1;
            fetchData();
          }
        });
      },
    });
  };
  const openRePass = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认重置此用户密码吗？重置后的密码为Hbkj@2024',
      onOk() {
        resetPassword({
          userId: item.userId,
        }).then((res) => {
          if (res.code == '200') {
            Message.success({
              //   content: res.message,
              content: '重置成功',
            });
          }
        });
      },
    });
  };

  const generateLockModel = () => {
    return {
      userIds: '',
    };
  };
  const lockForm = ref(generateLockModel());

  const lockShow = ref(false);
  const userIds = ref([]);

  const generateUploadModel = () => {
    return {
      file: null,
      userType: '',
      organizationId: '',
    };
  };

  const uploadRules = {
    file: [
      {
        required: true,
        message: '请选择附件',
      },
    ],
    userType: [
      {
        required: true,
        message: '请选择用户类型',
      },
    ],
    expirationTime: [
      {
        required: true,
        message: '请选择到期时间',
      },
    ],
  };
  const uploadForm = ref(generateUploadModel());
  const uploadShow = ref(false);
  const uploadModel = ref();
  const openUpload = () => {
    classList().then((res) => {
      console.log('获取班级列表', res.data);
      treeData.value = res.data;
    });
    uploadForm.value = generateDataModel();
    uploadShow.value = true;
  };

  const onChange = (fileList) => {
    if (fileList && fileList.length > 0) {
      uploadForm.value.file = fileList[0].file;
    } else {
      uploadForm.value.file = null;
    }
  };

  const uploadCheck = (done) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    uploadModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          let formData = new FormData();
          formData.append('organizationId', uploadForm.value.organizationId);
          formData.append('userType', uploadForm.value.userType);
          formData.append('expirationTime', uploadForm.value.expirationTime);

          formData.append('file', uploadForm.value.file);
          importUser(formData).then((res) => {
            if (res.code == '200') {
              Message.success({
                content: res.message,
              });
              reset();
              done(true);
            } else {
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const uploadCancel = () => {
    uploadShow.value = false;
  };

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    // onlyCurrent: false,
  });
  const userTypes = reactive([
    { id: 'TEACHER', name: '老师' },
    { id: 'STUDENT', name: '学生' },
    { id: 'VISITOR', name: '访客' },
  ]);
  const columns = computed<TableColumnData[]>(() => [
    {
      title: '账号',
      dataIndex: 'username',
    },
    {
      title: '姓名',
      dataIndex: 'nickname',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      slotName: 'sex',
      align: 'center',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      align: 'center',
    },
    // {
    //   title: '创建时间',
    //   dataIndex: 'createTime',
    //   slotName: 'createTime',
    //   align: 'center',
    // },
    {
      title: '有效期',
      dataIndex: 'expirationTime',
      align: 'expirationTime',
    },
    {
      title: '状态',
      dataIndex: 'status',
      slotName: 'status',
    },
    // {
    //   title: '部门',
    //   dataIndex: 'deptName',
    // },
    {
      title: '用户类型',
      dataIndex: 'userType',
      align: 'center',
      slotName: 'userType',
    },
    // {
    //   title: '班级ID',
    //   dataIndex: 'organizationId',
    //   align: 'center',
    // },
    {
      title: '班级名称',
      dataIndex: 'organizationName',
      align: 'center',
    },
    {
      title: '信用分',
      dataIndex: 'userCredit',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'option',
      slotName: 'option',
      align: 'center',
    },
  ]);

  const sexs = useSelectionStore().sexs;

  const generateFormModel = () => {
    return {
      username: '',
      nickname: '',
      sex: '',
      userType: '',
    };
  };

  const fieldnames = {
    key: 'id', // 节点的值，即选中节点的 id
    title: 'name', // 节点显示的文本，即节点的 name
    children: 'children', // 子节点的字段名，默认为 'children'
  };
  const rolesFieldsd = {
    key: 'id', // 节点的值，即选中节点的 id
    title: 'name', // 节点显示的文本，即节点的 name
    children: 'children', // 子节点的字段名，默认为 'children'
  };
  const formModel = ref(generateFormModel());
  const renderData = ref([]);
  const userList = ref();

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  const treeDatas = ref([]);
  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      userListd(data).then((res) => {
        let list = res.data.list || [];
        // list.map((item) => {
        //   item.disabled = item.isLocking == 1 ? false : true;
        // });
        renderData.value = list;
        pagination.total = res.data.total;
        pagination.current = res.data.pageNum;

        userList.value.selectAll(false);
      });
      organizationTree().then((res) => {
        treeDatas.value = res.data;
        console.log('测试', res.data);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };

  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
  };

  const downloadUser = () => {
    adminUserExport(formModel.value).then((res) => {});
  };

  const rolesFields = {
    value: 'roleId',
    label: 'roleName',
  };

  const getAppointmentTypes = (openAppointment: string) => {
    const types = openAppointment.split(','); // 将字符串按逗号分割成数组
    return types.map((type: string) => getAppointmentType(type)).join(', '); // 调用 getAppointmentType 转换为中文后再连接成字符串
  };
  const getAppointmentType = (type: string): string => {
    switch (type) {
      case 'TEACHER':
        return '老师';
      case 'STUDENT':
        return '学生';
      case 'VISITOR':
        return '访客';
      default:
        return '';
    }
  };
  function select(event) {
    console.log('选中', event);
    formModel.value.organizationId = event[0];
    onPageChange(1);
  }
  fetchData();
</script>
<style>
  .sszdbox {
    height: 670px;
    width: 295px;
    overflow: auto;
  }

  ::-webkit-scrollbar {
    width: 5px;
    height: 10px;
  }

  ::-webkit-scrollbar-track {
    width: 6px;
    background: rgba(#101f1c, 0.1);
    -webkit-border-radius: 2em;
    -moz-border-radius: 2em;
    border-radius: 2em;
  }

  ::-webkit-scrollbar-thumb {
    background-color: rgba(144, 147, 153, 0.5);
    background-clip: padding-box;
    min-height: 28px;
    -webkit-border-radius: 2em;
    -moz-border-radius: 2em;
    border-radius: 2em;
    transition: background-color 0.3s;
    cursor: pointer;
  }

  ::-webkit-scrollbar-thumb:hover {
    background-color: rgba(144, 147, 153, 0.3);
  }
</style>
